<?php

namespace App\Models;

use App\Http\Controllers\Resource\YtysController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/*数字资源（云图有声）model*/

class ResourceYtys extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_ytys';



    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom',
            'read_sum as read_number',
            'like_sum as vote_number',
            'collect_sum as collect_number'
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();

        if ($res) {
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取

            $res->read_number = format_number($res->read_number);
            $res->vote_number = format_number($res->vote_number);
            $res->collect_number = format_number($res->collect_number);
        }
        return $res;
    }


    /**
     * 添加数据到数据库
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['bookId'])) {
            return false;
        }

        $big_type_id = 2; //固定是有声书类型
        $res = $this->where('data_unique_id', $data['bookId'])->first(); //book_id 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        //  else {
        //     Log::channel('escmdlog')->debug('遇到相同数据' . $data['shId']);
        //     Log::channel('escmdlog')->debug($data);
        //     Log::channel('escmdlog')->debug($res->toArray());
        //     die;
        // }
        $res->book_id = $data['bookId'];
        $res->resource_business_id = 3; //固定3，云图有声
        $res->title = $data['bookName'];
        $res->big_type_id = $big_type_id;
        $res->type_id = $data['type_id'];
        $res->img = $data['cover'];
        $res->link = null;
        $res->isbn = null;
        $res->intro = $data['summary'];
        $res->author = $data['authorName'];
        $res->anchor_name = $data['anchorName'];
        $res->class_type_name = $data['classTypeName'];
        $res->press = $data['publishers'];
        $res->pre_time = $data['publishDate'];
        $res->chapters = $data['chapters'];
        $res->finished = $data['finished'];
        $res->collect_id = $data['collectId'];
        $res->history_id = $data['historyId'];
        $res->bought = $data['bought'];
        $res->show_chapters = $data['showChapters'];
        $res->listen_all = $data['listenAll'];
        $res->dept_id = $data['deptId'];
        $res->version_id = $data['versionId'];
        $res->class_id = $data['classId'];
        $res->type = $data['type'];
        $res->audio_duration = $data['audioDuration'];
        $res->audio_duration_time = $data['audioDurationTime'];
        $res->read_sum = $data['readSum'];
        $res->like_sum = $data['likeSum'];
        $res->collect_sum = $data['collectSum'];
        $res->original_create_time = $data['createTime'];
        $res->original_change_time = $data['updateTime'];
        $res->class_type_name = $data['classTypeName'];
        $res->data_unique_id = $data['bookId']; //数据唯一id
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->addData($res);

        return $res->id;
    }


    /**
     *删除下架数据
     */
    public function deleteData($book_id)
    {
        $res = $this->where('data_unique_id', $book_id)->where('is_del', 1)->first(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            return true;
        }
        $res->is_del = 2;
        $res->save();

        //删除总数据
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->deleteData($res->guid);

        return $res->id;
    }


    /**
     * 获取图书目录
     * @param guid  资源guid
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getBookCatalogue($guid, $page, $limit)
    {
        $key = md5('getYtysBookCatalogue-' . $guid . '-' . $page . '-' . $limit);
        $res = Cache::get($key);
        if (empty($res)) {
            $book_info = $this->select('book_id')->where('guid', $guid)->where('is_del', 1)->first();
            $book_id = trim($book_info['book_id']);
            if (empty($book_id)) {
                return false;
            }
            $ytysObj = new YtysController();
            $res = $ytysObj->getBookCatalogue($book_id, $page, $limit); //计算总条数
            if (!empty($res['data'])) Cache::set($key, $res, 24 * 60 * 60); //缓存一天
        }
        if (empty($res['data'])) {
            return null;
        }
        return $res;
    }

    /**
     * 获取图书资源地址
     * @param chapter_id  章节id
     */
    public function getYtysChapterAudioAddress($chapter_id)
    {
        $ytysObj = new YtysController();
        $res = $ytysObj->getAudioInfo($chapter_id);
        $data = [];
        if ($res) {
            $data['chapter_id'] = $res['data']['chapterid'];
            $data['book_id'] = $res['data']['bookId'];
            $data['rank'] = $res['data']['rank'];
            $data['audio_url'] = $res['data']['audioUrl'];
        }
        return $data;
    }
}
